<template>
	<view class="scrool-page">
		<!-- <view>
			<uni-data-select  v-model="value" :localdata="range" ></uni-data-select>			
		</view> -->
		<view class="list-cont">
			<scroll-view  class="scrool-more" style="height: 100%" scroll-y="true" scroll-with-animation="true">
				<view v-for="(item,index) in productList" :key="index">
					<uni-card :title="'序号:'+(index+1)" v-if="item.attr10=='1' || status=='3'" style='background-color: darkgrey;'>
						<text class="uni-body">物料编码：{{ item.itemCode }}</text><br>
						<text class="uni-body">数量：{{ item.qty }}</text><br>
						<text class="uni-body">库位：{{ item.storageAreaCode }}</text><br>
						<text class="uni-body">箱码：{{ item.boxCode }}</text><br>
					</uni-card>
					
					<uni-card :title="'序号:'+(index+1)" v-else>
						<text class="uni-body">物料编码：{{ item.itemCode }}</text><br>
						<text class="uni-body">数量：{{ item.qty }}</text><br>
						<text class="uni-body">库位：{{ item.storageAreaCode }}</text><br>
						<text class="uni-body">箱码：{{ item.boxCode }}</text><br>
					</uni-card>
				</view>
			</scroll-view>
		</view>
				
		<view class="footer">
			<button type="default" size='mini' @click="reduceData" style="width:48%; margin-left:1%;" v-if="!userflag">减码</button>
			<button type="default" size='mini' @click="reduceData" style="width:48%; margin-left:1%;" v-else>加箱</button>
			<button type="default" size='mini' @click="submit" style="width:49%; margin-left:1%;">完成</button>
		</view>
		
		<uni-popup ref="dataDialog" type="dialog" :is-mask-click="false">
			<uni-popup-dialog type="success" cancelText="关闭" confirmText="确定" title="提示" :before-close="true" content="检测到有缓存数据是否加载？" @confirm="dataConfirm"
				@close="dataClose">
			</uni-popup-dialog>
		</uni-popup>
	</view>
	
</template>

<script>
	import { getToken } from '@/utils/auth';
	import common from '../../pages/common/common.js'
	var main, receiver, filter;
	var ScanDeviceClass = plus.android.importClass("android.device.ScanDevice");
	var scanDevice;
	export default {
		data() {
			return {
				pkOrder:'',
				id:'',
				dataList:[],
				productList:[],
				locationCode:'',
				baseUrl:getApp().globalData.config.baseUrl,
				userName:this.$store.state.user.name,
				orgId:getApp().globalData.config.orgId,
				userflag:false,
				label: '单据类型',
				value: 'WmMsicShip',
				list:[],
			  //   range: [
					// { value: 'WmMsicShip', text: "标准杂发" },
					// { value: 'WmMsicShipExchange', text: "以货换货" },
					// { value: 'WmMsicShipUrgent', text: "紧急出货" },
			  //   ],
				title:'',
				status:'',
				index:'',
				sumbitFlag:false,
			}
		},
		
		onLoad: function (option) { //option为object类型，会序列化上个页面传递的参数
			this.orgId = uni.getStorageSync('orgId');
			this.id = option.id;
			this.pkOrder = option.pkOrder;
			this.title = option.title;
			this.status = option.status;
			this.index = option.index;
			uni.setNavigationBarTitle({
				title:this.title
			});
		},
		
		onHide: function() {
			this.unregisterScan();
		},
		
		destroyed: function() {
			this.unregisterScan();
		},
		
		onBackPress(options) {
			var that = this;
			if (options.from === 'navigateBack') {
			     return false;
			}
			//that.unregisterScan();
			let pages = getCurrentPages();  //获取所有页面栈实例列表
			let nowPage = pages[ pages.length - 1];  //当前页页面实例
			let prevPage = pages[ pages.length - 2 ];  //上一页页面实例
			var count =0;
			for(var i=0;i<that.productList.length;i++){
				if(that.productList[i].attr10 == '1'){				
					count = count+1;
				}
			}
			if(!this.sumbitFlag && count>0){
				try{
					uni.setStorageSync('wm_misc_ship'+this.id, this.productList);
				}catch(e){
					console.log(e.message);
				}
			}
			prevPage.$vm.chooseTab(that.index);
			uni.navigateBack({  //uni.navigateTo跳转的返回，默认1为返回上一级
			    delta: 1
			});
			return true;
		},
		
		onShow() {
			scanDevice = new ScanDeviceClass();
			scanDevice.openScan(); // 打开扫描
			scanDevice.setOutScanMode(0); // 扫描模式				
			this.initScan();
			this.registerScan();
		},
		
		mounted(){
			this.orgId = uni.getStorageSync('orgId');
			const value = uni.getStorageSync('wm_misc_ship'+this.id);
			if(value.length > 0){
				this.list = value;
				this.$refs.dataDialog.open();
			}else{
				this.queryBatch(this.pkOrder);
				this.list = [];
				this.productList = [];
			}
			this.queryBatch(this.pkOrder);
		},
		
		methods: {			
			initScan() {
				let _this = this;
				main = plus.android.runtimeMainActivity(); //获取activity  
				var IntentFilter = plus.android.importClass('android.content.IntentFilter');
				filter = new IntentFilter();
				filter.addAction("scan.rcv.message"); // 换你的广播动作  
				receiver = plus.android.implements('io.dcloud.feature.internal.reflect.BroadcastReceiver', {
					onReceive: function(context, intent) {
						plus.android.importClass(intent);
						let code = intent.getByteArrayExtra('barocode');
					    let codeStr = common.utf8ByteToUnicodeStr(code);
						scanDevice.stopScan(); // 停止扫描	
						if(_this.status =='2'){
							uni.showToast({
								title: '任务已挂起，请先恢复',
								icon: 'none',
								duration: 3000
							});
							return;
						}
						
						if(_this.status =='3'){
							uni.showToast({
								title: '任务已完成，不能修改',
								icon: 'none',
								duration: 3000
							});
							return;
						}
						_this.buttonScan(codeStr);
						_this.viewScan(codeStr);																	
					}
				});				
			},
			
			queryBatch(id){
				uni.request({
					url:that.baseUrl+'/system/TransferIn/find-one-by-id?id='+id,
					data:{
						id : id,
					},
					method: 'GET',
					header:{
						'authorization': getToken()
					},
					dataType:'json',
					success: (res) =>{
						var code = res.data.code;
						if(code == '200'){
							this.dataList = res.data.data;
							this.productList = res.data.data.boxList;
						}else{
							uni.showToast({
								title: res.data.msg,
								icon: 'none',
								duration: 3000
							});
						}
					}
				})
			},
			
			registerScan() {
				main.registerReceiver(receiver, filter);
			},
			
			unregisterScan() {
				main.unregisterReceiver(receiver);
			},
			
			buttonScan(codeStr){
				var that = this;
				if(that.userflag){
					return;
				}
				//显示加载框
				uni.showLoading({
				    title: '加载中',
					mask:true
				});
				var result = common.scanCode(codeStr);
				if(result[0] != "C"){
					//隐藏加载框
					uni.hideLoading();
					uni.showToast({
						title: '请正确扫描箱号',
						icon: 'none',
						duration: 5000
					});
					return;
				}
				var flag = 0;
				var data = '';
				for(var i=0;i<that.productList.length;i++){
					data = that.productList[i];
					if(data.boxCode == result[1]){
						if(data.attr10 == '1'){
							flag = 1;
						}else{
							flag = 2;
						}
						break;
					}
				}
				if(flag == 0){
					//隐藏加载框
					uni.hideLoading();
					uni.showToast({
						title: '此箱码不存在',
						icon: 'none',
						duration: 5000
					});
					return;
				}else if(flag == 1){
					//隐藏加载框
					uni.hideLoading();
					uni.showToast({
						title: '此箱码已经扫描',
						icon: 'none',
						duration: 5000
					});
					return;
				}else{
					that.queryDataByBoxCode(result[1],data)
					//隐藏加载框
					uni.hideLoading();
				}
			},
			
			//根据箱号查询条码主档的信息
			queryDataByBoxCode(codeStr,data){
				uni.showLoading({
					title: "加载中",
					mask:true
				});
				var that = this;
				uni.request({
					url:that.baseUrl+'/system/barcode/box',
					data:{
						userName:that.userName,
						boxCode:codeStr	,
						orgId:that.orgId,
					},
					method: 'POST',
					header:{
						'authorization':  getToken()
					},
					dataType:'json',
					success: (res) =>{
						if(res.data.code == '200' || res.data.code == 200) {	
							var result = res.data.data;														
							if(result.isFreeze == '1'){
								uni.hideLoading();
								uni.showToast({
									title: '此箱已被占用，请检查',
									icon: 'none',
									duration: 5000
								});
								return;
							}
							if(result.isStocked == '0'){
								uni.hideLoading();
								uni.showToast({
									title: '此箱不在库，请检查',
									icon: 'none',
									duration: 5000
								});
								return;
							}
							if(result.occupation == '1'){
								uni.hideLoading();
								uni.showToast({
									title: '此箱已冻结，请检查',
									icon: 'none',
									duration: 5000
								});
								return;
							}
							if(result.itemCode != data.itemCode){
								uni.hideLoading();
								uni.showToast({
									title: codeStr+'的物料编码为'+result.itemCode+"与"+data.itemCode+"不符",
									icon: 'none',
									duration: 5000
								});
								return;
							}
							data.attr10 = '1';
							that.prompt();
							uni.hideLoading();
						}else{
							//隐藏加载框
							uni.hideLoading();
							uni.showToast({
								title: res.data.msg,
								icon: 'none',
								duration: 5000
							});
							return;
						}
						
					},							
				})
			},
			
			viewScan(codeStr){
				if(!this.userflag){
					return;
				}
				var result = common.scanCode(codeStr);
				if(result[0] != "C"){
					uni.showToast({
						title: '请正确扫描编码',
						icon: 'none',
						duration: 5000
					});
					return;
				}
				var tempList = [];
				for(var i=0;i<this.productList.length;i++){
					if(result[1] == this.productList[i].boxCode){
						this.productList[i].attr10 = '';
					}
					tempList.push(this.productList[i]);				
				}
				this.productList = tempList;
				this.prompt();
			},
			
			reduceData(){
				if(this.status =='2'){
					uni.showToast({
						title: '任务已挂起，请先恢复',
						icon: 'none',
						duration: 3000
					});
					return;
				}
				
				if(this.status =='3'){
					uni.showToast({
						title: '任务已完成，不能修改',
						icon: 'none',
						duration: 3000
					});
					return;
				}
				if(this.userflag){
					this.userflag = false;
				}else{
					this.userflag = true;
				}
			},
			
			submit(){
				var that = this;
				if(that.status =='2'){
					uni.showToast({
						title: '任务已挂起，请先恢复',
						icon: 'none',
						duration: 3000
					});
					return;
				}
				
				if(that.status =='3'){
					uni.showToast({
						title: '任务已完成，不能修改',
						icon: 'none',
						duration: 3000
					});
					return;
				}
				uni.showLoading({
					title: "加载中",
					mask:true
				});
				var count =0;
				for(var i=0;i<that.productList.length;i++){
					if(that.productList[i].attr10 == '1'){				
						count = count+1;
					}
				}
				if(count == that.productList.length){
					that.dataList.boxList = that.productList;
					var wmMiscShipBox = {userName:that.userName,productList:that.dataList,orgId:that.orgId};
					var wmsBacklog = {id:that.id,executor:that.userName,orgId:that.orgId,startTime:'',endTime: new Date().toISOString().slice(0, 10),status:'3'};
					uni.request({
						url:that.baseUrl+'/system/WmMiscShip/newbatchUpdateWmMiscShipBox',
						data:{
							wmMiscShipBox : JSON.stringify(wmMiscShipBox),						
							wmsBacklog : wmsBacklog							
						},
						method: 'POST',
						header:{
							'authorization':  getToken()
						},
						dataType:'json',
						success: (res) =>{		
							console.log(res.data);
							if(res.data.code == '200' || res.data.code == 200) {
								that.sumbitFlag = true;
								//that.updateTask();
								uni.showToast({
									title: '操作成功并且代办任务已完成',
									icon: 'none',
									duration: 3000
								});	
								let pages = getCurrentPages();  //获取所有页面栈实例列表
								let nowPage = pages[ pages.length - 1];  //当前页页面实例
								let prevPage = pages[ pages.length - 2 ]; 
								prevPage.$vm.chooseTab(that.index);
								setTimeout(function(){
									uni.navigateBack({  //uni.navigateTo跳转的返回，默认1为返回上一级
										delta: 1
									});								
								},1000);
							}else{
								uni.hideLoading();
								uni.showToast({
									title: res.data.msg,
									icon: 'none',
									duration: 3000
								});
								return;
							}									
						},							
					})
				}else{
					if(count > 0){
						uni.hideLoading();
						uni.showModal({
								title: '提示',
								content: '此杂发单还未完成是否临时保存?',
								success: function(res) {
								if (res.confirm) {
									uni.setStorageSync('wm_misc_ship'+that.id, that.productList);
									//that.unregisterScan();
									setTimeout(function(){
										let pages = getCurrentPages();  //获取所有页面栈实例列表
										let nowPage = pages[ pages.length - 1];  //当前页页面实例
										let prevPage = pages[ pages.length - 2 ];  //上一页页面实例
										prevPage.$vm.chooseTab(that.index);	
										uni.navigateBack({  //uni.navigateTo跳转的返回，默认1为返回上一级
											delta: 1
										});
									},1000);
								} else {											
									return;
								}
							}
						})
					}else{
						uni.hideLoading();
						uni.showToast({
							title: '杂发单未扫描任何数据，不能完成',
							icon: 'none',
							duration: 3000
						});
						return;
					}
				}			
			},
			
			updateTask(){
				var that = this;
				//显示加载框
				uni.showLoading({
				    title: '加载中',
					mask:true
				});
				uni.request({
					url:that.baseUrl+'/system/wmsbacklog/update',
					data:{
						id:	that.id,
						executor:that.userName,
						orgId:that.orgId,
						startTime:'',
						endTime: new Date().toISOString().slice(0, 10),
						status:'3'//完成状态
					},
					method: 'POST',
					header:{
						'authorization':  getToken()
					},
					dataType:'json',
					success: (res) =>{
						//隐藏加载框
						uni.hideLoading();
						//that.unregisterScan();
						if(res.data.code == '200' || res.data.code == 200) {	
							uni.showToast({
								title: '操作成功并且代办任务已完成',
								icon: 'none',
								duration: 3000
							});	
							let pages = getCurrentPages();  //获取所有页面栈实例列表
							let nowPage = pages[ pages.length - 1];  //当前页页面实例
							let prevPage = pages[ pages.length - 2 ]; 
							prevPage.$vm.chooseTab(that.index);
							setTimeout(function(){
								uni.navigateBack({  //uni.navigateTo跳转的返回，默认1为返回上一级
									delta: 1
								});								
							},1000);							
						}else{
							uni.showToast({
								title: res.data.msg,
								icon: 'none',
								duration: 3000
							});
							return;
						}
						
					},			
				})
			},	
			
			dataConfirm(){
				this.productList = this.list;
				try {
					uni.removeStorageSync('wm_misc_ship'+this.id);
				} catch (e) {
					console.log(e.message);
				}
				this.$refs.dataDialog.close();
			},
			
			dataClose(){
				this.list = [];
				try {
					uni.removeStorageSync('wm_misc_ship'+this.id);
				} catch (e) {
					console.log(e.message);
				}
				this.queryBatch(this.pkOrder);
				this.$refs.dataDialog.close();
			},
			
			prompt(type){
				var innerAudioContext = uni.createInnerAudioContext();
				innerAudioContext.autoplay = true;
				innerAudioContext.src = '/static/mp3/success.mp3';
				//innerAudioContext.play();//铃声文件的路径
				//innerAudioContext.stop();
				innerAudioContext.onPlay(() => {
				  console.log('开始播放');
				});
				innerAudioContext.onError((res) => {
				  console.log(res.errMsg);
				  console.log(res.errCode);
				});
				innerAudioContext.onPause(function() {  
					console.log('end');  
					innerAudioContext.destroy()  
				})  					
			},
		}
	}
</script>

<style lang="scss">
	.main {
		background-color: #fff;
		height: 300upx;
		align-items: center;
		margin-top: 10upx;
	}
	.text-content {
		font-size: 48rpx;
		text-align: center;
	}
	
	.city {
		/* #ifndef APP-PLUS-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
		align-items: center;
		justify-content: flex-start;
		// width: 160rpx;
		margin-left: 4px;
		font-size: 26rpx;
	}
	
	.input-view {
		display: flex;
		flex-direction: row;
		flex: 1;
		//background-color: #f8f8f8;
		height: 30px;
		padding: 0 80px;
		flex-wrap: nowrap;
		margin: 7px 0;
		line-height:30px;
		font-size: 26rpx;
	}
	page {
		width: 100%;
		height: 100%;
	}
	
	
	.scrool-page {
		display: flex;
		flex-direction: column;
		width: 100%;
		height: 100%;
	}
	
	.header-cont {
		width: 100%;
		height: 110rpx;
		line-height: 100rpx;
		text-align: center;
		// background: red;
	}
	
	.list-cont {
		flex: 1;
		position: relative;
	
		.scrool-more {
			position: absolute;
			left: 0;
			right: 0;
			top: 0;
			bottom: 0;
		}
	
		.list {
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			background: #e0e0e0;
	
		}
	}
	
	
	.footer {
		color: #fff;
		line-height: 100rpx;
		flex: 0 0 100rpx;
		/* 不放大不缩小固定100rpx */
	}
</style>


